package com.jiutong.meipengdai.ui.activitys;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jiutong.meipengdai.R;
import com.jiutong.meipengdai.base.BaseActivity;
import com.jiutong.meipengdai.common.Constants;
import com.jiutong.meipengdai.entity.BankCardInfoRespond;
import com.jiutong.meipengdai.entity.BindingCardRespond;
import com.jiutong.meipengdai.http.present.CommonPresent;
import com.jiutong.meipengdai.http.subscribers.SubscriberOnNextListener;
import com.jiutong.meipengdai.lianlianPay.BaseHelper;
import com.jiutong.meipengdai.lianlianPay.PayConstants;
import com.jiutong.meipengdai.lianlianPay.MobileSecurePayer;
import com.jiutong.meipengdai.lianlianPay.PayOrder;
import com.jiutong.meipengdai.utils.SpConfig;
import com.orhanobut.logger.Logger;

import org.json.JSONObject;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by suxi on 2017/6/20.
 */

public class AddBankCardActivity extends BaseActivity {
    @Bind(R.id.rl_back)
    RelativeLayout rlBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_real_name)
    TextView tvRealName;
    @Bind(R.id.et_bankcard)
    EditText etBankcard;
    @Bind(R.id.et_id_card)
    EditText etIdCard;
    @Bind(R.id.btn_add)
    Button btnAdd;
    private BankCardInfoRespond.DataBean resultData;
    private Handler mHandler = createHandler();

    @Override
    public int getLayoutResouceId() {
        return R.layout.activity_add_bankcard;
    }

    @Override
    protected void initView() {
        super.initView();
        ButterKnife.bind(this);
        tvTitle.setText("添加银行卡");
        tvRealName.setText(SpConfig.getInstance().getString(Constants.REALNAME_STRING));
    }

    @OnClick({R.id.rl_back, R.id.btn_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_back:
                finish();
                break;
            case R.id.btn_add:

                if (TextUtils.isEmpty(getBankNumber())) {
                    toastShortShow("请输入银行卡号");
                    break;
                }

                if (TextUtils.isEmpty(getIdCard())) {
                    toastShortShow("请输入身份证号码");
                    break;
                }

                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("cardNo", getBankNumber());
                CommonPresent.checkBankCard(mContext, new SubscriberOnNextListener<BankCardInfoRespond>() {
                    @Override
                    public void onNext(BankCardInfoRespond result) {

                        resultData = result.getData();
                        if ("200".equals(result.getResCode())) {

                            HashMap<String, Object> fieldMap = new HashMap<>();
                            fieldMap.put("idType", "0");
                            fieldMap.put("idNo", getIdCard());
                            fieldMap.put("acctName", tvRealName.getText().toString());
                            fieldMap.put("cardNo", getBankNumber());
                            fieldMap.put("cardType", result.getData().getCardType());
                            fieldMap.put("bankName", result.getData().getBankName());
                            fieldMap.put("bankCode", result.getData().getBankCode());
                            fieldMap.put("signSource", "2");
                            CommonPresent.bankCardBinding(mContext, new SubscriberOnNextListener<BindingCardRespond>() {
                                @Override
                                public void onNext(BindingCardRespond respond) {

                                    BindingCardRespond.DataBean data = respond.getData();

                                    PayOrder payOrder = constructPreCardPayOrder(data);
                                    String content4Pay = BaseHelper.toJSONString(payOrder);
                                    MobileSecurePayer msp = new MobileSecurePayer();
                                    boolean bRet = msp.pay(content4Pay, mHandler,
                                            PayConstants.RQF_PAY, AddBankCardActivity.this, "1", false, false);
                                    Logger.e("content4Pay == " + content4Pay);
                                }

                                @Override
                                public void onError(Throwable e) {

                                }
                            }, fieldMap);

                        } else {
                            toastShortShow("请输入正确的银行卡号");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                }, hashMap);
                break;


        }
    }

    private Handler createHandler() {
        return new Handler() {
            public void handleMessage(Message msg) {
                String strRet = (String) msg.obj;
                switch (msg.what) {

                    case PayConstants.RQF_PAY: {
                        JSONObject objContent = BaseHelper.string2JSON(strRet);
                        String retCode = objContent.optString("ret_code");
                        String retMsg = objContent.optString("ret_msg");

                        // 成功
                        if (PayConstants.RET_CODE_SUCCESS.equals(retCode)) {
                        // TODO 卡前置模式返回的银行卡绑定协议号，用来下次支付时使用，此处仅作为示例使用。正式接入时去掉
//                            if (pay_type_flag == 1) {
//                                TextView tv_agree_no = (TextView) findViewById(R.id.tv_agree_no);
//                                tv_agree_no.setVisibility(View.VISIBLE);
//                                tv_agree_no.setText(objContent.optString(
//                                        "agreementno", ""));
//                            }
//                            BaseHelper.showDialog(AddBankCardActivity.this, "提示",
//                                    "支付成功，交易状态码：" + retCode +" 返回报文:"+strRet,
//                                    android.R.drawable.ic_dialog_alert);

                            finish();
                        }
//                        else
//
//                        if (PayConstants.RET_CODE_PROCESS.equals(retCode)) {
//                            // TODO 处理中，掉单的情形
//                            String resulPay = objContent.optString("result_pay");
//                            if (PayConstants.RESULT_PAY_PROCESSING
//                                    .equalsIgnoreCase(resulPay)) {
//                                BaseHelper.showDialog(AddBankCardActivity.this, "提示",
//                                        objContent.optString("ret_msg") + "交易状态码："
//                                                + retCode + " 返回报文:" + strRet,
//                                        android.R.drawable.ic_dialog_alert);
//                            }
//
//                        } else {
//                            // TODO 失败
//                            BaseHelper.showDialog(AddBankCardActivity.this, "提示", retMsg
//                                            + "，交易状态码:" + retCode + " 返回报文:" + strRet,
//                                    android.R.drawable.ic_dialog_alert);
//                        }
                    }
                    break;
                }
                super.handleMessage(msg);
            }
        };

    }

    private PayOrder constructPreCardPayOrder(BindingCardRespond.DataBean data) {

        PayOrder order = new PayOrder();
        order.setOid_partner(data.getOidPartner());
        order.setUser_id(data.getUserId());
        order.setSign_type(data.getSignType());
        order.setSign(data.getSign());
        order.setBusi_partner(data.getBusiPartner());
        order.setNo_order(data.getNoOrder());
        order.setDt_order(data.getDtOrder());
        order.setName_goods(data.getNameGoods());
        order.setInfo_order(data.getInfoOrder());
        order.setMoney_order(data.getMoneyOrder());
        order.setValid_order(data.getValidOrder());
        order.setPay_type(data.getPayType());
        order.setRisk_item(data.getRiskItem());
//        order.setId_type(data.getIdType());
        order.setId_no(data.getIdNo());
        order.setAcct_name(data.getAcctName());
        order.setFlag_modify(data.getFlagModify());
        order.setCard_no(data.getCardNo());
        order.setNotify_url(data.getNotifyUrl());
        order.setBank_code(resultData.getBankCode());
        order.setForce_bank("0");
        order.setValid_order(data.getValidOrder());

        return order;
    }

    public String getBankNumber() {
        return etBankcard.getText().toString().trim();
    }

    public String getIdCard() {
        return etIdCard.getText().toString().trim();
    }

}
